// import router from '@/lib/router';
import Vue from 'vue';
import Router from 'vue-router';
import { setToken, setCookieTenant, getUserToken } from '@/lib/auth'; // get token from cookie

Vue.use(Router);
import store from '@/extend/store';
import { beforeRouter, afterRouter } from '@/lib/router/permission';
import extendRouter from './module/index';
import { api_GET_UsersOrganizationUnit } from '@/extend/api/swaggerApi/identity';

// const whiteList = [/^\/[\s\S]+\/(register|info)/]; // no redirect whitelist
const whiteList = [/^\/home\/[\s\S]+\/info/, /^\/home\/[\s\S]+\/info\/[gameData|brackets|athlete|medal|committee]/];
const createRouter = (aRouterList) => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: aRouterList
});

const router = createRouter(extendRouter);
// 路由跳转检测
router.beforeEach((to, from, next) => {
  if (to.query.token) {
    if (!store.state.app.isgetBadge) {
      setToken(to.query.token);
    }
  }
  if (!store.state.app.isgetBadge && !/^\/myCenter/.test(to.path)) {
    let tenantId = to.params.id
      ? to.params.id.lastIndexOf('_') > -1
        ? to.params.id.substring(to.params.id.lastIndexOf('_') + 1)
        : ''
      : '';
    tenantId = tenantId || to.query.tenantid;
    setCookieTenant(tenantId);
  }
  if (store.state.user.token && store.state.user.currentUserType) {
    initToDo(to, next);
  }
  beforeRouter(to, from, next, store, router, extendRouter, whiteList, initToDo);
  // 处理跳转/myCenter的问题
  if (store.state.user.currentUserType && store.state.user.currentUserType.userType && to.path === '/myCenter') {
    const userType = store.state.user.currentUserType && store.state.user.currentUserType.userType || {};
    if (userType.code === 'Delegation') {
      next({ path: '/myCenter/team/info' });
    } else {
      next({ path: '/myCenter/individual/info' });
    }
  } else {
    next();
  }
});

router.afterEach(() => {
  afterRouter();
});

// 初始化只执行一次的操作
async function initToDo (to, next) {
  const _toPath = to.path;
  const _delegationId = store.state.user.currentUserType.delegationId;
  const _info = store.state.user.info;
  if (!store.state.app.isgetBadge) {
    await getUserToken();
  }
  // 跳转到团体
  if (_toPath.indexOf('/myCenter/team') > -1 || _toPath.indexOf('/myCenter/approval') > -1) {
    /**
     * 团体信息的展示
     * (1) 在后台中没有加入机构 - 新账号（可以创建团体）
     * (2) 在后台中加入了机构且有团体会员管理（EventsManagement.Competitions.MembersManagement）权限
    */
    if (!_delegationId) {
      api_GET_UsersOrganizationUnit().then(res => {
        if (!res) {
          next();
        } else {
          next({ path: '/404' });
        }
      });
    } else if (_delegationId && _info.permissions.includes('EventsManagement.Competitions.MembersManagement')) {
      next();
    } else {
      next({ path: '/404' });
    }
  }
  return true;
}

export default router;
